const jwt = require('jsonwebtoken');
const logger = require('../config/logger');

// JWT认证中间件
const authMiddleware = (req, res, next) => {
  try {
    const token = req.header('Authorization')?.replace('Bearer ', '');
    
    if (!token) {
      return res.status(401).json({
        code: 401,
        message: '未提供访问令牌',
        data: null,
        timestamp: Date.now()
      });
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    
    logger.info(`用户 ${decoded.id} 访问接口: ${req.method} ${req.path}`);
    next();
  } catch (error) {
    logger.error('JWT认证失败:', error);
    return res.status(401).json({
      code: 401,
      message: '无效的访问令牌',
      data: null,
      timestamp: Date.now()
    });
  }
};

// 管理员权限中间件
const adminMiddleware = (req, res, next) => {
  if (req.user.role !== 'admin') {
    logger.warn(`用户 ${req.user.id} 尝试访问管理员接口: ${req.path}`);
    return res.status(403).json({
      code: 403,
      message: '权限不足',
      data: null,
      timestamp: Date.now()
    });
  }
  next();
};

// 可选认证中间件（用于某些可选登录的接口）
const optionalAuthMiddleware = (req, res, next) => {
  try {
    const token = req.header('Authorization')?.replace('Bearer ', '');
    
    if (token) {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      req.user = decoded;
    }
    
    next();
  } catch (error) {
    // 认证失败但不阻断请求
    next();
  }
};

module.exports = {
  authMiddleware,
  adminMiddleware,
  optionalAuthMiddleware
}; 